package com.cdel.akka.inbox;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Inbox;
import akka.actor.Props;
import akka.actor.Terminated;

import com.typesafe.config.ConfigFactory;

public class Demo {

	public static void main(String[] args) throws TimeoutException {
		ActorSystem system = ActorSystem.create("inboxdemo", ConfigFactory.load("samplehello.conf"));
		ActorRef worker = system.actorOf(Props.create(MyWorker.class), "worker");

		//actorSystem构造了一个与之绑定的邮箱inbox，接着使用邮箱监视MyWorker，这样就能在MyWorker停止后得到一个消息。
		final Inbox inbox = Inbox.create(system);
		inbox.watch(worker);
		//通过邮箱向MyWorker发送消息
		inbox.send(worker, MyWorker.Msg.WORKING);
		inbox.send(worker, MyWorker.Msg.DONE);
		inbox.send(worker, MyWorker.Msg.CLOSE);

		//进行消息接收，如果发现MyWorker已经停止工作，则关闭整个actorSystem
		while(true){
			Object msg = inbox.receive(Duration.create(1, TimeUnit.SECONDS));
			if(msg == MyWorker.Msg.CLOSE){
				System.out.println("My worker is closing");
			}else if(msg instanceof Terminated){
				System.out.println("My worker is dead");
				system.shutdown();
				break;
			}else{
				System.out.println(msg);
			}
		}
	}

}
